const { createOrder, findAllOrder, updateOrder } = require('../service/order.service')
const { orderAddError } = require("../constant/err.type")

class OrderController {
    async create(ctx, next) {
        const { address_id, goods_info, total } = ctx.request.body
        const user_id = ctx.state.user.id
        // 订单编号生成
        const oredr_number = 'order' + Date.now()
        // 操作数据库 
        try {
            const res = await createOrder({ user_id, address_id, goods_info, total, oredr_number })
            // 返回客户端
            ctx.body = {
                code: 0,
                message: "添加订单成功",
                result: res
            }
        } catch (err) {
            console.error(err)
            ctx.app.emit('error', orderAddError, ctx)
        }
    }
    async findAll(ctx, next) {
        const user_id = ctx.state.user.id
        const { pageSize = 10, pageNum = 1, state = 0 } = ctx.request.query
        const res = await findAllOrder(pageNum, pageSize, state, user_id)
        ctx.body = {
            code: 0,
            message: '获取订单数据成功',
            result: res
        }
    }
    async update(ctx) {
        const id = ctx.request.params.id
        const { state } = ctx.request.body
        const res = await updateOrder(id, state)
        ctx.body = {
            code: 0,
            message: '更新订单状态成功',
            result: res[0]
        }
    }
}
module.exports = new OrderController()